<template>
  <div class="login">
    <n-spin>
      <template #description>
        正在进入系统中...
      </template>
    </n-spin>
  </div>
</template>

<script>
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/store/modules/user'
import { signinRedirectCallback, signoutRedirectCallback, signoutRedirect, getPath, removePath } from '@/utils/oidc/index.js'

export default {
  name: 'LoginPage',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const userStore = useUserStore()
    if (route.query?.code && route.query?.state) {
      /* 登录后的回调 */
      signinRedirectCallback().then(res => {
        // router.push({ path: getPath() })
        // removePath()
        // userStore.getUserInfos(res.profile.userName)
        /* 判断返回的授权信息是否能访问该平台 */
        // console.log(res)
        const { authority } = res.profile
        const { VITE_PLATFORM, VITE_CLIENT_ID } = import.meta.env
        const clientRoleList = res.profile?.clientRoleList || []
        const { roleId } = clientRoleList.length > 1 ? clientRoleList?.find((item) => item.clientId === VITE_CLIENT_ID) || { roleId: null } : (clientRoleList || { roleId: null })
        if (authority && (authority.includes(VITE_PLATFORM))) {
          // fetchPermission({ roleId, clientId: 'tuoheng-waterway-admin' })
          //   .then(res => {
          //     const { opMenusList } = res.data
          //     const path = opMenusList[0].path
          //     router.push(path)
          //   })
          router.push('/')
        } else {
          $message.error('暂无权限访问，请联系管理员')
          setTimeout(() => {
            signoutRedirect()
          }, 2000)
        }
      }).catch(err => {
        console.log(err)
        /* 失败则退出登录 */
        signoutRedirect()
      })
      // } else if (getPath()) {
      //   signoutRedirectCallback().then(res => {
      //     router.push({ path: getPath() })
      //     userStore.setUserInfo()
      //     removePath()
      //   })
    } else {
      router.push('/')
    }
  }
}

</script>
<style scoped lang='scss'>
.login{
  width: 100vw;
  height: 100vh;
  position: relative;
  .n-spin-body{
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
}
</style>
